package com.example.service;

import com.example.decoder.RpcDecoder;
import com.example.handler.UserServiceHandler;
import com.example.request.RpcRequest;
import com.example.serialization.JSONSerializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @author lbq
 * @version 1.0
 * @date 2021/2/3 22:31
 */
public class UserServiceImpl implements UserService {

    @Override
    public String sayHello(String msg) {
        System.out.println("are you ok ? " + msg);
        return "are you ok ? " + msg;
    }

    public static void startServer(String ip, int port) throws InterruptedException {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(new UserServiceHandler());
                    }
                });

        serverBootstrap.bind(ip, port).sync();
    }
}
